package home.contaduria.web;

import home.contaduria.domain.Client;
import home.contaduria.domain.Expense;
import home.contaduria.domain.ExpenseType;
import home.contaduria.service.ExpenseService;
import home.contaduria.service.ExpenseTypeService;
import home.contaduria.support.util.WebUtil;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/expenses")
public class ExpenseController {
    private ExpenseService expenseService;
    private ExpenseTypeService expenseTypeService;

    @Autowired
    public ExpenseController(ExpenseService expenseService, ExpenseTypeService expenseTypeService) {
        this.expenseService = expenseService;
        this.expenseTypeService = expenseTypeService;
    }

    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
        uiModel.addAttribute("expense", new Expense());
        WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
        return "expenses/create";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String create(@Valid Expense expense, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("expense", expense);
            WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
            return "expenses/create";
        }
        uiModel.asMap().clear();

        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        expense.setClient(client);
        expenseService.createExpense(expense);

        return "redirect:/expenses/" + WebUtil.encodeUrlPathSegment(expense.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model uiModel) {
        WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
        uiModel.addAttribute("expense", expenseService.readExpense(id));
        uiModel.addAttribute("itemId", id);
        return "expenses/show";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            uiModel.addAttribute("expenses", expenseService.listExpenses(client, page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) expenseService.countExpensesNumber(client) / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("expenses", expenseService.listExpenses(client));
        }
        WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
        return "expenses/list";
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("expense", expenseService.readExpense(id));
        WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
        return "expenses/update";
    }

    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Expense expense, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("expense", expense);
            WebUtil.addDateTimeFormatPatterns(uiModel, "expense_operationdate_date_format");
            return "expenses/create";
        }
        uiModel.asMap().clear();

        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        expense.setClient(client);
        expenseService.updateExpense(expense);

        return "redirect:/expenses/" + WebUtil.encodeUrlPathSegment(expense.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        expenseService.deleteExpense(id);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/expenses";
    }

    @ModelAttribute("expenseTypes")
    public Collection<ExpenseType> populateExpenseTypes() {
        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return expenseTypeService.loadClientExpenseTypes(client);
    }

}
